<template>
  <div class="member-index">
    <!-- <tx-list-query
      @query="$handleQuery()"
      cleanText="清除查询条件"
      :table="table"
    >
      <tx-field-input
        :entity="table.query"
        name="orgName"
        label="成员单位名称"
        placeholder="请输入成员单位名称"
        @done="$handleInputQuery()"
      />
      <tx-field-input
        :entity="table.query"
        name="name"
        label="管理员姓名"
        placeholder="请输入管理员姓名"
        @done="$handleInputQuery()"
      />
    </tx-list-query> -->

    <tx-block>
      <div v-if="!$currentUserInfo">
        <tx-button-add :name="generateTitle()" @click="add" />
        <div class="btnbox-right">
          <tx-button-add
            :icon="allowSort ? '' : 'el-icon-tickets'"
            :name="allowSort ? '保存排序' : '修改排序'"
            @click="updateSort"
          />

          <el-tooltip
            v-if="!allowSort"
            class="item"
            effect="dark"
            content="点击后进入修改排序模式，用户可以自行手动拖拽调整"
            placement="bottom-start"
          >
            <div class="tooltip"></div> </el-tooltip
          ><tx-button-add
            v-if="allowSort"
            icon=""
            name="取消排序"
            class="dialog-cancel-btn"
            style="background: #1d3f6a"
            @click="cancelSort"
          />
        </div>
      </div>
      <div
        v-else
        style="
          padding-bottom: 10px;
          display: flex;
          align-items: center;
          color: #fff;
        "
      >
        <span style="flex: 1">当前位置：{{ this.stepsLocationName }}</span>
        <div class="btnbox-right">
          <tx-button-add icon="" name="返回上一级" @click="handlePreLevel" />
        </div>
      </div>
      <el-form ref="form" :model="form" label-width="0px">
        <tx-list-table
          :table="table"
          ref="listTable"
          row-key="name"
          v-loading="table.loading"
        >
          <tx-table-column-text label="排序" width="60">
            <template slot-scope="scope"
              ><span class="number-index">{{
                scope.scope.scope.$index + 1
              }}</span></template
            >
          </tx-table-column-text>
          <tx-table-column-text label="内设机构名称">
            <template slot-scope="scope">
              <tx-table-input
                :entity="scope.row"
                name="office"
                :action="scope.row.$action"
                :rules="$rule.requireds('请输入内设机构名称')"
                :prop="buildRowProp(scope, 'office')"
                placeholder="请输入内设机构名称"
              />
            </template>
          </tx-table-column-text>
          <tx-table-column-text label="管理员姓名">
            <template slot-scope="scope">
              <tx-table-input
                :entity="scope.row"
                name="name"
                :action="scope.row.$action"
                :rules="$rule.requireds('请输入管理员姓名')"
                :prop="buildRowProp(scope, 'name')"
                placeholder="请输入管理员姓名"
              />
            </template>
          </tx-table-column-text>

          <tx-table-column-text label="职务">
            <template slot-scope="scope">
              <tx-table-input
                :entity="scope.row"
                name="job"
                :action="scope.row.$action"
                :rules="$rule.requireds('请输入职务')"
                :prop="buildRowProp(scope, 'job')"
                placeholder="请输入管理员职务"
              />
            </template>
          </tx-table-column-text>
          <tx-table-column-text label="手机号" width="160">
            <template slot-scope="scope">
              <tx-table-input
                :entity="scope.row"
                name="phone"
                :action="scope.row.$action"
                :rules="$rule.mobile('手机号', true)"
                :prop="buildRowProp(scope, 'phone')"
                placeholder="请输入手机号"
              />
            </template>
          </tx-table-column-text>
          <tx-table-column-text label="可添加最大人数">
            <template slot-scope="scope">
              <tx-table-input
                :entity="scope.row"
                required
                name="maxUserNumber"
                :action="scope.row.$action"
                :rules="[
                  ...$rule.integer('请输入正确的数字'),
                  {
                    required: true,
                    message: '请输入可添加最大人数',
                    trigger: 'blur',
                  },
                ]"
                :prop="buildRowProp(scope, 'maxUserNumber')"
                placeholder="请输入可添加最大人数"
              />
              <!-- <span>{{scope.row.maxUserNumber}}</span> -->
            </template>
          </tx-table-column-text>
          <tx-table-column-text label="已添加用户数">
            <template slot-scope="scope">
              <span>{{ scope.row.userNumber }}</span>
            </template>
          </tx-table-column-text>
          <tx-table-column-action width="270" align="left" :key="$columnKey()">
            <template slot-scope="scope">
              <el-form
                :ref="`form${scope.scope.scope.$index}`"
                :model="form.record"
                :rules="formRules"
                style="display: none"
              >
                <!-- <tx-form-input :entity="form.record" name="orgName" /> -->
                <tx-form-input :entity="form.record" name="name" />
                <tx-form-input :entity="form.record" name="office" />
                <tx-form-input :entity="form.record" name="job" />
                <tx-form-input :entity="form.record" name="maxUserNumber" />
                <tx-form-input :entity="form.record" name="phone" />
              </el-form>
              <!-- <tx-link text="编辑" name="dept" :query="{itemId: scope.row.itemId}"  />
                        <tx-link text="删除" name="dept" :query="{itemId: scope.row.itemId}"  />  -->
              <el-button
                type="primary"
                size="mini"
                v-if="scope.row.$action != 'modify' && !$currentUserInfo"
                class="table-edit-btn"
                @click="handleEdit(scope)"
                >编辑
              </el-button>
              <el-button
                type="primary"
                size="mini"
                v-if="scope.row.$action != 'modify' "
                class="table-edit-btn"
                @click="handleSQ(scope)"
                >业务授权
              </el-button>
              <el-button
                type="primary"
                size="mini"
                v-if="scope.row.id && scope.row.$action != 'modify'"
                class="table-edit-btn"
                @click="handleLevelDetail(scope)"
                >详情
              </el-button>
              <el-button
                type="primary"
                size="mini"
                v-if="scope.row.$action == 'modify'"
                @click="handleSave(scope)"
                class="table-save-btn"
                v-preventReClick="3000"
                >保存
              </el-button>
              <el-button
                size="mini"
                type="warning"
                v-if="scope.row.$action == 'modify'"
                @click="handleCancel(scope)"
                class="table-cancel-btn"
                >取消
              </el-button>
              <!-- <el-button
                size="mini"
                type="danger"
                v-if="scope.row.$action != 'modify'"
                @click="handleDelete(scope)"
                class="table-del-btn"
                >删除
              </el-button> -->

              <tx-button-text-delete
                class="table-del-btn"
                v-if="
                  scope.row.$action == 'modify' &&
                  !disabledEdit(scope.row.phone)
                "
                controller="OrgController"
                :body="scope.row"
                :idValue="scope.row.id"
                :success="$handleQuery"
                target="记录"
              />
            </template>
          </tx-table-column-action>
        </tx-list-table>
        <!-- {{
          $nextTick(() => {
            $initDragTable($refs["listTable"], table.page, "records");
          })
        }} -->
      </el-form>
    </tx-block>
    <validate-phone
      @success="SubmitEvent"
      :form="form.record"
      ref="validatePhone"
    ></validate-phone>
    <nsjg-ywsc ref="NsjgYwsc"></nsjg-ywsc>
  </div>
</template>

<script>
import TxTableInput from "@/components/tx/tx-form/TxTableInput.vue";
import NsjgYwsc from "./components/nsjg-ywsc.vue";
// 内设机构
export default {
  components: { TxTableInput, NsjgYwsc },
  name: "member-org-own",
  data() {
    return {
      allowSort: false,
      beforeSortData: "",
      table: {
        records: [],
        loading: false,
        query: {
          orgName: "",
          name: "",
        },
        sort: {
          descs: ["updateTime"],
        },
        page: this.$yzvue.initPage(),
      },

      dict: {
        name: "成员单位",
      },
      form: {
        record: {
          name: "",
          orgName: "",
          office: "",
          job: "",
          phone: "",
          maxUserNumber: 0,
        },
        records: [],
      },
      formRules: {
        name: this.$rule.name("姓名", null, 32),
        // orgName: this.$rule.name("单位", null, 32),
        job: this.$rule.name("职务", null, 32),
        maxUserNumber: this.$rule.integer("请输入正确的数字"),
        office: this.$rule.name("内设机构", null, 32),
        phone: this.$rule.mobile("手机号", true),
      },
    };
  },

  mounted() {
    this.loadTable();
  },
  computed: {
    disabledEdit() {
      return function (phone) {
        return (
          this.$userInfo.phone == phone &&
          ["1000000007", "1000000015", "1000000016"].includes(
            this.getParameter("menuId")
          )
        );
      };
    },
  },
  methods: {
    handleQuery() {
      this.loadTable();
    },
    async loadTable() {
      //   let param = this.getQueryParam();
      //   console.log("param", this.table.query);
      this.table.loading = true;
      // const { data } = await getList({ ...param, });
      let data = {
        body: {
          // orgName: this.table.query.orgName,
          // name: this.table.query.name,
          menuID: this.getParameter("menuId"),
          areaCode: this.$userInfo.areaCode,
          createdBy: this.$currentUserInfo?.phone || this.$userInfo.phone,
          areaName: "",
          orgId: this.$currentUserInfo?.orgId || this.$userInfo.orgId,
        },
      };
      this.$api.OrgController.list(data, (res) => {
        this.table.loading = false;
        console.log(res);
        for (let ri = 0; ri < res.data.length; ri++) {
          const re = res.data[ri];
          re.$action = "view";
        }
        this.$yzvue.assembleBody(this.table.page, { records: res.data });
        this.form.records = res.data;
        // this.$nextTick(() => {
        //   this.$initDragTable(
        //     this.$refs["partsTable"],
        //     this.table.page,
        //     "records",
        //     (res) => {
        //       console.log("sort", res);
        //     }
        //   );
        // });
        // this.form.records[this.form.records.length-1]["$action"] ="modify"
        console.log("this.form.records", this.form.records);
      });
    },

    buildRowProp($scope, field) {
      let {
        scope: { scope },
      } = $scope;
      return `records.${scope.$index}.${field}`;
    },

    getQueryParam() {
      let param = this.$yzvue.assemblePage(this.table);
      let query = this.table.query;
      this.$yzvue.appendFilter(param.body.filters, "name", "like", query.name);
      return param;
    },
    // 新增
    add() {
      Object.keys(this.form.record).forEach((v) => {
        this.form.record[v] = "";
      });
      let newRow = this.$lodash.cloneDeep({
        ...this.form.record,
        $action: "modify",
      });
      this.table.page.records.push(newRow);
    },
    // 编辑
    handleEdit($scope) {
      $scope.row.$action = "modify";
      $scope.row.$origin = {
        name: $scope.row.name,
        orgName: $scope.row.orgName,
        office: $scope.row.office,
        phone: $scope.row.phone,
        job: $scope.row.job,
        maxUserNumber: $scope.row.maxUserNumber,
      };
    },
    handleSQ($scope) {
      this.$refs.NsjgYwsc.handleEdit($scope);
    },
    // 保存
    handleSave($scope) {
      Object.assign(this.form.record, $scope?.row || {});
      let { id, phone } = this.form.record;
      this.$handleFormValidate(`form${$scope.scope.scope.$index}`, async () => {
        // 如果是编辑情况下改了手机号，或者新增
        if (
          ($scope.row.id && $scope.row.$origin.phone != phone) ||
          !$scope.row.id
        ) {
          let res = await this.$existAd(id, phone);
          if (res?.data) {
            this.$refs.validatePhone.init();
            return false;
          }
        }
        this.SubmitEvent();
      });
    },
    // 保存
    SubmitEvent($scope) {
      let { id, name, orgName, job, maxUserNumber, office, phone } =
        this.form.record;
      let pack = {};
      if (id) {
        pack.body = {
          id,
          name,
          orgName,
          job,
          maxUserNumber,
          phone,
          office,
          menuID: this.getParameter("menuId"),
          areaCode: this.$userInfo.areaCode,
          createdBy: this.$userInfo.phone,
        };
      } else {
        pack.body = {
          name,
          // orgName,
          job,
          phone,
          office,
          maxUserNumber,
          menuID: this.getParameter("menuId"),
          areaCode: this.$userInfo.areaCode,
          createdBy: this.$userInfo.phone,
          orgId: this.$currentUserInfo?.orgId || this.$userInfo.orgId,
          orgName: this.$currentUserInfo?.orgName || this.$userInfo.orgName,
        };
      }

      this.table.loading = true;
      let newMethod = this.$api.AdminController.new;
      let updateMethod = this.$api.AdminController.update;
      this.$invokeSave(pack, "id", newMethod, updateMethod, async (res) => {
        this.table.loading = false;
        if (res && res?.code == 0) {
          this.form.record.$action = "view";
          await this.loadTable();
          if (!pack.body.id) {
            if (this.$userInfo.inheritAuth) {
              // 默认继承了权限，不需要弹窗授权
              return false;
            }
            // 如果是新增创建管理员账号，保存成功后，默认弹窗授权业务
            let rowScope = {
              row: this.table?.page?.records.filter(
                (item) => item.phone == phone
              )?.[0],
            };
            this.$refs.NsjgYwsc.handleEdit(rowScope || $scope);
          }
        }
      });
      this.table.loading = false;
    },
    // 取消
    handleCancel($scope) {
      Object.assign($scope.row, $scope.row.$origin);
      $scope.row.$action = "view";
      this.$refs["form"].clearValidate();
    },
    //删除
    handleDelete($scope) {
      let { id, name, orgId, job, office, phone } = $scope.row;
      let {
        scope: { scope },
      } = $scope;
      if (orgId) {
        this.$api.OrgController.delete(
          { body: { id, orgId, createdBy: this.$userInfo.phone } },
          (res) => {
            if (res.code == 0) {
              this.loadTable();
            }
          }
        );
      } else {
        this.table.page.records.splice(scope.$index, 1);
      }
      // 请求后台接口删除数据库数据
    },
    updateSort() {
      if (this.allowSort == false) {
        this.$initDragTable(
          this.$refs["listTable"],
          this.table.page,
          "records"
        );
        this.beforeSortData = JSON.parse(
          JSON.stringify(this.table.page.records)
        );
      } else {
        let params = this.table.page.records
          ?.filter((i) => i.id)
          ?.map((i, k) => {
            return {
              id: i.orgId,
              udOrder: k + 1,
            };
          });
        this.$api.OrgController.sort({ body: params }, (res) => {
          if (res.code == 0) {
            this.loadTable();
            this.$stopDragTable();
          }
        });
      }
      this.allowSort = !this.allowSort;
    },
    cancelSort() {
      this.allowSort = !this.allowSort;
      // this.this.table.page.records = this.beforeSortData
      // this.$initDragTable(this.$refs["listTable1"],
      //       this.table.page,
      //       "records1")
      this.$stopDragTable();
      this.loadTable();
    },
    // 重置按钮文本
    generateTitle() {
      // let userOrgName=this.$userInfo.orgName;
      // let orgNames=["应急厅","应急局","应急管理局","应急管理厅"]
      // if(orgNames.includes(userOrgName) ){
      //   return  "内设机构"
      // }
      return "安全生产、防灾减灾内设机构";
    },
  },
};
</script>

<style lang="scss">
.main-container .member-index {
  .tx-list-query {
    margin: 0px;

    // border: 2px solid $c-bd-menu;
  }
  .tx-block {
    width: auto;
    margin: 15px 0px;
    background-color: $c-bg-query;
    border: 1px solid $c-bd-content;
  }

  .el-table td.el-table__cell {
    padding: 8px 0px 0px 0px;
    .cell > span {
      display: block;
      padding-bottom: 13px;
      line-height: 30px;
    }
    .tx-table-column-action {
      display: block;
      padding-bottom: 10px;
    }

    .el-input__inner {
      height: 30px;
      line-height: 30px;
      padding: 0px 5px;
    }
    .el-form-item {
      margin-bottom: 13px;
    }
    .el-form-item__content {
      line-height: 30px;
    }
    .el-form-item__error {
      padding-top: 0px;
    }
  }
}
.btnbox-right {
  display: flex;
  align-items: center;
  float: right;
  .tooltip {
    margin-left: 10px;
    width: 16px;
    height: 16px;
    cursor: pointer;
    background: url("~@/assets/TeamAdministrator/icon_explain.png") no-repeat;
  }
}
</style>
